using UnityEngine;
using System;
using System.IO;

[ System.Serializable ]
public class SATexture
{
	public int ID;
	public int terrainID;

	public short px;
	public short py;

	public short w;
	public short h;

	public byte e;
	public byte s;

	public byte flag;

	public Color32[] color32;
	public Texture2D texture2D;
	public Sprite sprite;
	public bool hasData;

	public Vector2 pivot;

	public void initData()
	{
		if ( texture2D != null ) 
		{
			return;
		}

		hasData = false;

		texture2D = new Texture2D( w , h , TextureFormat.ARGB32 , false , false );
		texture2D.filterMode = FilterMode.Point;
		texture2D.wrapMode = TextureWrapMode.Clamp;

		pivot = new Vector2( (float)-px / (float)w , (float)( h + py ) / (float)h );

		sprite = Sprite.Create( texture2D , new Rect( 0.0f , 0.0f , w , h ) , 
		                       pivot , GameSetting.GameScale , 0 , SpriteMeshType.FullRect );
	}


	public void releaseData()
	{
		if ( texture2D == null )
		{
			return;
		}

//		if ( ID <= 4574 )
//		{
//			// terrain not release
//			return;
//		}

		Texture2D.Destroy( texture2D );
		texture2D = null;

		Sprite.Destroy( sprite );
		sprite = null;

		hasData = false;
	}


	public void loadData()
	{
		string path = "Textures/" + ID.ToString() + ".imgz" ;
		
		FileStream stream = File.Open( GameSetting.StreamingAssetsPath + path , FileMode.Open , FileAccess.Read );
		
		byte[] com = new byte[ stream.Length ];
		stream.Read( com , 0 , (int)stream.Length );
		byte[] dcom = GameDefine.DeCompress( com );
		
		setColor( dcom );
		
		stream.Close();
	}


	public void setColor( byte[] data )
	{
		if ( hasData )
		{
			return;
		}

		color32 = new Color32[ w *  h ];

		int c = 0;
		for ( int i = 0 ; i < h ; i++ )
		{
			for ( int j = 0 ; j < w ; j++ )
			{
				color32[ j + ( h - i - 1 ) * w ] = SAPalConfig.instance.PAL[ data[ c ] ];
				c++;
			}
		}

		if ( w == 0 || h == 0 )
		{
			return;
		}

		hasData = true;

		texture2D.SetPixels32( color32 );
		texture2D.Apply( false );
	}


	public SATexture ()
	{
		
		
		
	}
	
	
}


